import { useEffect, useState, useCallback } from 'react';
import { message, Popover, Select } from 'antd';
import { Button, Pagination, Row, Col, Modal, Input, Spin, Empty } from 'antd';
import dayjs from 'dayjs';
import debounce from 'lodash.debounce';
import api from '@/api/account';
import CustomizeHeader from '@/components/customizeHeader/customizeHeader';
import { useNavigate } from 'react-router-dom';
import UserEvent from '@/components/userEvent';
import FilterModal from '@/components/filterModal';
import { userList, userDelete } from '@/api/user';
import moment from 'moment';
interface listParams {
    pageNum: number;
    keyword: string;
    status: string;
    minAge: number;
    maxAge: number;
    userGender: any;
    professionId: string;
    personality: string;
    disabled: any;
    currentProvinceCode: string;
    currentCityCode: string;
    currentDistrictCode: string;
    creatioTime: any;
    sTime: string;
    eTime: string;
}
interface DataType {
    userName: string;
    userMobile: string;
    Gender: number;
    personality: string;
    age: number;
    createTime: number;
    disabled: boolean;
    userId: string;
    userGenderText: string;
    lastActiveTimeText: string;
    nickname: string;
    deleteTime: string;
    lastActiveTime: string;
    fullName: string;
}
const User = props => {
    const link = useNavigate();
    const [loading, setLoading] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
    const [totalRecord, setTotalRecord] = useState(0);
    const [totalActive, setTotalActive] = useState(0);
    const [titleText, setTitleText] = useState<string>('Delete account');
    const [contentTextOne, setContentTextOne] = useState<string>('After confirmation, the user will be deleted.');
    const [contentTextTwo, setContentTextTwo] = useState<string>('This action cannot be undone.');
    const [confirmText, setConfirmText] = useState<string>('Confirm');
    const [openType, setOpenType] = useState<number>(0);
    const [listParams, setListParams] = useState<listParams>({
        pageNum: 1,
        keyword: '',
        status: '',
        minAge: 0,
        maxAge: 200,
        userGender: null,
        professionId: '',
        personality: '',
        disabled: null,
        currentProvinceCode: '',
        currentCityCode: '',
        currentDistrictCode: '',
        creatioTime: [],
        sTime: '',
        eTime: '',
    });
    // const [listParams, setListParams] = useState<listParams>({});
    const [tableData, setTableData] = useState<DataType[]>([]);
    const inputChange = e => {
        debouncedSave({ ...listParams, keyword: e.target.value, pageNum: 1 });
    };
    const debouncedSave = useCallback(
        debounce(nextValue => setListParams(nextValue), 1500),
        []
    );
    function getAccountList() {
        const {
            keyword,
            minAge,
            maxAge,
            userGender,
            professionId,
            personality,
            disabled,
            currentProvinceCode,
            currentCityCode,
            currentDistrictCode,
            creatioTime,
            sTime,
            eTime,
            pageNum,
        } = listParams;
        console.log(listParams, '接口');
        // const startTime =
        //     creatioTime && creatioTime.length > 0 ? moment(creatioTime[0]).format('YYYY-MM-DD HH:mm:ss') : '';
        // const endTime =
        //     creatioTime && creatioTime.length > 0 ? moment(creatioTime[1]).format('YYYY-MM-DD HH:mm:ss') : '';
        // console.log(creatioTime, startTime, endTime);
        // api.accountList(apiParams, res => {
        //     setLoading(false);
        //     if (res.code === 200) {
        //         setTableData(res.data.records);
        //         setTotalRecord(res.data.total);
        //     } else {
        //         message.error(res.message);
        //     }
        // });
        // api.accountList({ ...apiParams, status: 1 }, res => {
        //     setLoading(false);
        //     if (res.code === 200) {
        //         setTotalActive(res.data.total);
        //     } else {
        //         message.error(res.message);
        //     }
        // });
        const params = {
            ...listParams, // 先注释，方便看接口返回的数据
            keyword,
            minAge,
            maxAge,
            userGender,
            professionId,
            personality,
            disabled,
            currentProvinceCode,
            currentCityCode,
            currentDistrictCode,
            pageNum,
            pageSize: 10,
            startTime: sTime,
            endTime: eTime,
        };
        setLoading(true);
        userList(params).then((res: any) => {
            setLoading(false);
            if (res && res.records.length > 0) {
                res.records.map(item => {
                    if (item.userGender == 1) {
                        item.userGenderText = 'Male';
                    } else if (item.userGender == 2) {
                        item.userGenderText = 'Female';
                    } else {
                        item.userGenderText = '-';
                    }
                    item.lastActiveTime =
                        item.lastActiveTime && item.lastActiveTime !== '0'
                            ? moment(item.lastActiveTime).format('DD/MM/YYYY HH:mm:ss')
                            : '-';
                    item.createTime =
                        item.createTime && item.createTime !== '0'
                            ? moment(item.createTime).format('DD/MM/YYYY HH:mm:ss')
                            : '-';
                });
                setTableData(res.records);
                setTotalRecord(res.total);
            } else {
                setTableData([]);
                setTotalRecord(0);
            }
        });
    }
    const handlePageChange = prop => {
        console.log(prop, 111);
        setListParams(state => ({ ...state, pageNum: prop }));
    };
    useEffect(() => {
        getAccountList();
    }, [listParams]);
    const handleCancel = () => {
        // setDetailModalOpen(false);
    };
    const handleChange = (value: string) => {
        setListParams(state => ({ ...state, status: value === 'all' ? '' : value, pageNum: 1 }));
    };
    const [accountModal, setAccountModal] = useState({ userId: '', open: false, isDelete: false, disabled: false });
    const modifyStatus = (userId: string, isDisable: string) => {
        const formData = new FormData();
        formData.append('isDisable', isDisable);
        api.accountActive(userId, formData, res => {
            if (res.code === 200) {
                setListParams(state => ({ ...state }));
                setAccountModal({ isDelete: false, open: false, userId: '', disabled: false });
            } else {
                message.error(res.message);
            }
        });
    };
    const [viewMoreIndex, setViewMoreIndex] = useState(-1);
    const confirmCallBack = value => {
        if (value === 1) {
            const params = {
                userId: accountModal.userId,
            };
            setConfirmLoading(true);
            userDelete(params).then(res => {
                setConfirmLoading(false);
                getAccountList();
                setAccountModal({ userId: '', open: false, isDelete: false, disabled: false });
            });
        } else {
            getAccountList();
        }
    };
    function getValueFromSon(values) {
        // values是子组件filterModal传过来的值
        const {
            professionId,
            disabled,
            ageRange,
            creatioTime,
            personality,
            residence,
            userGender,
            sTime,
            eTime,
            currentProvinceCode,
            currentCityCode,
            currentDistrictCode,
        } = values;
        const ageList = ageRange ? ageRange.split('-') : [];
        const minAge = ageList.length > 0 ? ageList[0] : 0;
        const maxAge = ageList.length > 0 ? ageList[1] : 100;
        const obj = {
            ...listParams,
            minAge,
            maxAge,
            userGender,
            professionId,
            personality,
            disabled,
            currentProvinceCode,
            currentCityCode,
            currentDistrictCode,
            // keyword,
            creatioTime,
            residence,
            sTime,
            eTime,
        };
        console.log(obj);
        // setListParams(state => ({
        //     ...state,
        //     minAge,
        //     maxAge,
        //     userGender,
        //     professionId,
        //     personality,
        //     disabled,
        //     // currentProvinceCode,
        //     // currentCityCode,
        //     // currentDistrictCode,
        //     // keyword,
        //     creatioTime,
        //     residence,
        //     sTime,
        //     eTime,
        // }));
        setListParams(obj);
        setFilterVisible(false);
        // 调用查询
        // getAccountList();
    }
    const toDetail = (userId: string) => {
        sessionStorage.setItem('userId', userId);
        link('/user/detail');
    };
    const openModal = (obj: any, type: number) => {
        let conTextOne = 'After confirmation, the user will be deleted.';
        let conTextTwo = 'This action cannot be undone.';
        let conConfirmText = 'Confirm';
        let titleText = 'Active account';
        if (type === 1) {
            // 已经禁用了，要设置为启用
            conTextOne =
                'Are you sure to active this account?  After the account is suspended, the user cannot log in.';
            conTextTwo = '';
            conConfirmText = 'Confirm';
            titleText = 'Active account';
        } else if (type === 2) {
            // 已经启用了，要设置为禁用
            conTextOne =
                'Are you sure to suspend this account?  After the account is suspended, the user cannot log in.';
            conTextTwo = '';
            conConfirmText = 'Confirm';
            titleText = 'Suspend account';
        } else {
            // 删除账号
            conTextOne = 'After confirmation, the user will be deleted.';
            conTextTwo = 'This action cannot be undone.';
            conConfirmText = 'Delete';
            titleText = 'Delete account';
        }
        setContentTextOne(conTextOne);
        setContentTextTwo(conTextTwo);
        setConfirmText(conConfirmText);
        setTitleText(titleText);
        setOpenType(type);
        setAccountModal({
            open: true,
            userId: obj.userId,
            isDelete: false,
            disabled: obj.disabled,
        });
    };
    const [filterVisible, setFilterVisible] = useState(false);
    return (
        <>
            <div className="page-main account">
                <div className="container">
                    <div className="search-bar">
                        <div className="page-title">User management</div>
                        <div className="search-bar-right">
                            <Input
                                className="search-input"
                                placeholder="Search"
                                onChange={inputChange}
                                prefix={
                                    <img
                                        src={require('@/assets/images/search-icon.png')}
                                        style={{ width: 20, height: 20 }}
                                    />
                                }
                            />
                            <div className="filter-btn" onClick={() => setFilterVisible(true)}>
                                Filter
                                <img src={require('@/assets/images/filtering.png')} alt="filter-btn" />
                            </div>
                        </div>
                    </div>
                    <div className="table">
                        <div className="table-th">
                            <Row>
                                {/* <Col span={2}>ID</Col> */}
                                <Col span={2}>User name</Col>
                                <Col span={2}>Nick name</Col>
                                <Col span={3}>Mobile number</Col>
                                <Col span={2}>Gender</Col>
                                <Col span={2}>Personality</Col>
                                <Col span={2}>Age</Col>
                                <Col span={4}>Registration date</Col>
                                <Col span={4}>Last active time</Col>
                                <Col span={2}>Status</Col>
                                <Col span={1}></Col>
                            </Row>
                        </div>
                        {loading ? (
                            <div className="data_loading flex-center">
                                <Spin tip="Loading" />
                            </div>
                        ) : tableData.length ? (
                            tableData.map((item, index) => (
                                <Row className="table-tr" key={item.userId}>
                                    {/* <Col span={2}>{item.userId}</Col> */}
                                    <Col span={2}>{item.fullName || '-'}</Col>
                                    <Col span={2}>{item.nickname}</Col>
                                    <Col span={3}>{item.userMobile}</Col>
                                    <Col span={2}>{item.userGenderText}</Col>
                                    <Col span={2}>{item.personality || '-'}</Col>
                                    <Col span={2}>{item.age}</Col>
                                    <Col span={4}>{item.createTime || '-'}</Col>
                                    <Col span={4}>{item.lastActiveTime || '-'}</Col>
                                    <Col span={2}>
                                        <div className={item.disabled ? 'Suspend' : 'Active'}>
                                            {item.disabled ? 'Suspended' : 'Active'}
                                        </div>
                                    </Col>
                                    <Col span={1}>
                                        <Popover
                                            placement="bottomRight"
                                            content={
                                                <div className="view-more">
                                                    <div onClick={() => toDetail(item.userId)}>View details</div>
                                                    <div className="line"></div>
                                                    <div
                                                        className={item.disabled ? 'Active' : 'Suspend'}
                                                        onClick={() => {
                                                            if (item.disabled) {
                                                                // modifyStatus(item.userId, '0');
                                                                // setAccountModal({
                                                                //     open: true,
                                                                //     userId: item.userId,
                                                                //     isDelete: false,
                                                                // });
                                                                openModal(item, 1);
                                                            } else {
                                                                openModal(item, 2);
                                                                // setAccountModal({
                                                                //     open: true,
                                                                //     userId: item.userId,
                                                                //     isDelete: false,
                                                                // });
                                                            }
                                                        }}
                                                    >
                                                        {item.disabled ? 'Active Account' : 'Suspend Account'}
                                                    </div>
                                                    <div className="line"></div>
                                                    <div
                                                        className="remove-user"
                                                        onClick={() => {
                                                            // setAccountModal({
                                                            //     open: true,
                                                            //     userId: item.userId,
                                                            //     isDelete: true,
                                                            // });
                                                            openModal(item, 3);
                                                        }}
                                                    >
                                                        Remove account
                                                    </div>
                                                </div>
                                            }
                                        >
                                            <img
                                                style={{
                                                    width: 30,
                                                    height: 30,
                                                    cursor: 'pointer',
                                                }}
                                                onMouseEnter={() => {
                                                    setViewMoreIndex(index);
                                                }}
                                                onMouseLeave={() => {
                                                    setViewMoreIndex(-1);
                                                }}
                                                src={require(`@/assets/images/view-more${
                                                    viewMoreIndex === index ? '-enter' : ''
                                                }.png`)}
                                                alt=""
                                            />
                                        </Popover>
                                    </Col>
                                </Row>
                            ))
                        ) : (
                            // <div className="no-data flex-center">No users available.</div>
                            <div className="emptyBox">
                                <Empty description="No users available." />
                            </div>
                        )}
                    </div>
                    {totalRecord > 10 ? (
                        <div className="pagination flex-end">
                            <div
                                className={listParams.pageNum === 1 ? 'to-first is-disable' : 'to-first'}
                                onClick={() => {
                                    setListParams(state => ({ ...state, pageNum: 1 }));
                                }}
                            >
                                First
                            </div>
                            <Pagination
                                current={listParams.pageNum}
                                hideOnSinglePage
                                showSizeChanger={false}
                                total={totalRecord}
                                onChange={handlePageChange}
                            />
                            <div
                                className={
                                    totalRecord
                                        ? listParams.pageNum === Math.ceil(totalRecord / 10)
                                            ? 'to-last is-disable'
                                            : 'to-last'
                                        : 'to-last is-disable'
                                }
                                onClick={() => {
                                    setListParams(state => ({
                                        ...state,
                                        pageNum: Math.ceil(totalRecord / 10),
                                    }));
                                }}
                            >
                                Last
                            </div>
                        </div>
                    ) : (
                        ''
                    )}
                </div>
            </div>
            <UserEvent
                params={accountModal}
                onCancel={() => setAccountModal({ userId: '', open: false, isDelete: false, disabled: false })}
                confirmCallBack={confirmCallBack.bind(this)}
                openType={openType}
                titleText={titleText}
                contentTextOne={contentTextOne}
                contentTextTwo={contentTextTwo}
                confirmText={confirmText}
                btnLoading={confirmLoading}
            />
            <FilterModal
                open={filterVisible}
                onConfirm={getValueFromSon.bind(this)}
                onCancel={(isSearch: boolean) => {
                    setFilterVisible(false);
                    console.log(isSearch);
                }}
            />
        </>
    );
};

export default User;
